import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;
import java.util.Vector;

/**
 * 主类
 */
public class StudentList {
    static final int N = 200;
    static Vector<Student> arr = new Vector<Student>();

    private static String filePath = "D:\\Call\\Student.txt";


    public static void select() throws Exception{
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        
        for(int i = 0; i < 9; i++) {
            Student student = new Student();

            Random random = new Random();
            int randomNumber = random.nextInt(15) + 1;
            FileWriter fwriter = null;

            connection = DBUtil.getConnection();
            String sql = "select username, sex, studyNo, status from student where id = ? and state != 3";
            String sql2 = "update student set state = 3 where id = ?";
            ps = connection.prepareStatement(sql);
            ps.setInt(1, randomNumber);
            rs = ps.executeQuery();
            if (rs.next()) {
                String calledName = rs.getString("username");
                String calledSex = rs.getString("sex");
                String calledStudyNo = rs.getString("studyNo");
                boolean status = rs.getBoolean("status");

                student.setName(calledName);
                student.setSex(calledSex);
                student.setId(calledStudyNo);
                student.setState(status);

                arr.add(student);

                //把随机点到的学生写入txt文件
                String content = calledName + "\t" + calledStudyNo + "\t" + calledSex + "\t" + status + "\n";
                //FileWriter fwriter = null;
                try {
                    // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
                    fwriter = new FileWriter(filePath, false);
                    fwriter.write(content);
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        //fwriter.flush();
                        fwriter.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

                ps = connection.prepareStatement(sql2);
                ps.setInt(1, randomNumber);
                ps.executeUpdate();
            }
        }

        DBUtil.closeAll(connection, ps, rs);
    }

    public static void main(String[] args) throws Exception {
        select();
        new CallTheRoll(arr);// 开始
    }
}
